<?php
namespace app\index\controller;

use think\Controller;
use think\View;
use Jssdk\JSSDK;

class News extends Common {
    /**
     * 获取单页数据
     * @return \think\response\View
     */
    public function index() {
        $cid = input('param.cid', 0);
        $pid = input('param.pid', 0);

        $this->assign('cid', $cid);
        $this->assign('pid', $pid);

        // 获取分类列表
        $cate = model('category')->where('pid', $pid)->select();
        $this->assign('cate', $cate);

        // 获取文章列表
        $list = model('article')->where('category_id', $cid)->order('create_time desc')->paginate(12);
        $this->assign('list', $list);

        return view();
    }

    /**
     * 文章详情
     */
    public function info() {

        if (is_weixin()) {
            $jssdk = new JSSDK(config('wechat.appid'), config('wechat.appsecret'));
            $signPackage = $jssdk->getSignPackage();
            $this->assign('signPackage', $signPackage);
        }
        $id = input('param.id');

        // 修改文章点击数
        $hits = rand(1, 3);
        model('article')->where(['id' => $id])->setInc('hits', $hits);

        // 获取文章内容
        $data = model('article')->get(['id' => $id]);
        $this->assign('data', $data);

        // 获取分类内容
        $cate = model('category')->all(['pid' => $data->category->pid]);
        $this->assign('cate', $cate);

        // 获取上一篇
        $previous_posts =  model('article')->where(['id' => ['gt', $id]])->order('id asc')->find();
        $this->assign('previous_posts', $previous_posts);

        // 获取下一篇
        $next_chapter =  model('article')->where(['id' => ['lt', $id]])->order('id desc')->find();
        $this->assign('next_chapter', $next_chapter);

        // 获取推荐内容
        $recommend = model('article')->order('id desc')->limit(5)->select();
        $this->assign('recommend', $recommend);

        return view();
    }
}
